import APIClient from "../network/index"

const cartModule = {
    state: {
        listItems: [],
        cartItems: JSON.parse(localStorage.getItem("cart")) || [],
        allSelected: JSON.parse(localStorage.getItem("allSelected")) || false
    },
    mutations: {
        getList(state, items) {
            state.listItems = items;
        },
        addItemToCart(state, item) {
            //判断购物车是否存在该商品
            var flag = false;
            state.cartItems.every((element) => {
                if (element.id === item.id) {
                    flag = true;
                    element.count++
                }
            })

            if (!flag) {
                item.checked = false;
                item.count = 1;
                state.cartItems.push(item);
            }
            localStorage.setItem("cart", JSON.stringify(state.cartItems))
        },
        changeItemStatus(state, item) {
            state.cartItems.forEach((element) => {
                if (element.id === item.id) {
                    element.checked = item.checked
                }
            })

            state.allSelected = state.cartItems.every((element) => {
                return element.checked === true
            })

            localStorage.setItem("cart", JSON.stringify(state.cartItems))
            localStorage.setItem("allSelected", JSON.stringify(state.allSelected))
        },
        changeAllselect(state, boolean) {
            state.allSelected = boolean;

            state.cartItems.forEach((element) => {
                element.checked = boolean;
            })

            localStorage.setItem("cart", JSON.stringify(state.cartItems))
            localStorage.setItem("allSelected", JSON.stringify(state.allSelected))
        }
    },
    actions: {
        getList(context) {
            APIClient.getGoodsList()
            .then((res) => {
                // window.console.log(res.data.data)
                context.commit("getList", res.data.data.data.list)
            }).catch((error) => {
                window.console.log(error)
            })
        },
        addItemToCart(context, item) {
            context.commit("addItemToCart", item)
        },
        changeItemStatus(context, item) {
            context.commit("changeItemStatus", item)
        },
        changeAllselect(context, boolean) {
            context.commit("changeAllselect", boolean)
        }
    },
    modules: {

    }
}

export default cartModule
